package com.kyang.musiconline.service;

import com.kyang.musiconline.dao.VinylDao;
import com.kyang.musiconline.model.Vinyl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author kyang
 */
@Slf4j
@Service
public class VinylService {
    @Autowired
    private VinylDao vinylDao;

    public boolean addMusic(Vinyl vinyl) {
        log.info("addMusic");
        return vinylDao.insert(vinyl);
    }

    public boolean delMusic(String vinylId) {
        log.info("delMusic");
        return vinylDao.deleteById(vinylId);
    }

    public boolean updateMusic(Vinyl vinyl) {
        log.info("updateMusic");
        return vinylDao.update(vinyl);
    }

    public Vinyl getMusicInfo(String vinylId) {
        try {
            log.info("Get Music Info by Id: {}", vinylId);
            return vinylDao.getVinylById(vinylId);
        } catch (EmptyResultDataAccessException e) {
            log.error("Music is deleted or not existed: {}", e.getMessage());
            return null;
        }
    }

    public List<Vinyl> getUserVinyl(String userId) {
        try {
            List<Vinyl> list = vinylDao.getAllVinylByUser(userId);
            if (list != null && !list.isEmpty()) {
                log.info("Get all vinyl by user: {}", userId);
                return list;
            }
            return null;
        } catch (EmptyResultDataAccessException e) {
            log.error("User's Vinyl not exists: {}", e.getMessage());
            return null;
        }
    }

    public List<Vinyl> getAllVinylByKeyword(String keyword) {
        try {
            List<Vinyl> list = vinylDao.getVinylByKeyWords(keyword);
            if (list != null && !list.isEmpty()) {
                log.info("Search Vinyl by keyword: {}", keyword);
                return list;
            }
            return null;
        } catch (EmptyResultDataAccessException e) {
            log.error("Search Vinyl not exists: {}", e.getMessage());
            return null;
        }
    }

    public List<Vinyl> getIndex() {
        try {
            List<Vinyl> list = vinylDao.getTwelveVinyls();
            if (list != null && !list.isEmpty()) {
                log.info("Get numbers of twelve vinyls: {}", list.size());
                return list;
            }
            return null;
        } catch (EmptyResultDataAccessException e) {
            log.error("Get Vinyls failed: {}", e.getMessage());
            return null;
        }
    }
}
